package com.surekam.mnai.service;

import java.util.Date;
import java.util.HashSet;
import java.util.Set;

import javax.annotation.Resource;

import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.transaction.annotation.Transactional;

import com.surekam.mnai.dao.UserDao;
import com.surekam.mnai.model.MNAIUser;

@Transactional(readOnly = true)
public class UserDetailsServiceImpl implements UserDetailsService {

	@Resource
	private UserDao userDao;

	/**
	 * 获取用户Detail信息的回调函数.
	 */
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException,
			DataAccessException {

		MNAIUser user = userDao.loginByUserNumberAndPassword(username);
		if (user == null) {
			throw new UsernameNotFoundException("用户" + username + " 不存在");
		}

		Set<GrantedAuthority> grantedAuths = obtainGrantedAuthorities(user);

		// showcase的User类中无以下属性,暂时全部设为true.
		boolean enabled = true;
		boolean accountNonExpired = true;
		boolean credentialsNonExpired = true;
		boolean accountNonLocked = true;

		OperatorDetails userDetails = new OperatorDetails(user.getUserNumber(),
				user.getUserPassword(), enabled, accountNonExpired, credentialsNonExpired,
				accountNonLocked, grantedAuths);
		
		//把中文名字加入
		userDetails.setName(user.getName());
		// 加入登录时间信息和用户角色
		userDetails.setLoginTime(new Date());
//		userDetails.setRoleList(user.getRoleList());
		
		return userDetails;
	}

	/**
	 * 获得用户所有角色的权限.
	 */
	private Set<GrantedAuthority> obtainGrantedAuthorities(MNAIUser user) {
		Set<GrantedAuthority> authSet = new HashSet<GrantedAuthority>();

		authSet.add(new GrantedAuthorityImpl("ROLE_ADMIN"));

		return authSet;
	}

}
